from django.shortcuts import render

# Create your views here.
from django.views import View

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from apps.areas.models import Area
from utils.response_code import RETCODE
from utils.views import LoginRequiredMixin, LoginRequiredJSONMixin
import logging
from django.http import HttpResponseBadRequest

logger = logging.getLogger('django')

from django.core.cache import cache
#收货地址
class AreasView(View):

    def get(self, request):
        #查询省市区id
        area_id = request.GET.get('area_id')

        if not area_id:

            province_list = cache.get('province_list')
            if not province_list:
                try:
                    province_model_list = Area.objects.filter(parent__isnull=True)
                    province_list = []
                    for provice_model in province_model_list:
                        province_list.append({'id':provice_model.id, 'name':provice_model.name})
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '省份数据错误'})
                cache.set('province_list', province_list, 24*3600)

                #返回响应数据
            return JsonResponse({'code':RETCODE.OK, 'errmsg':'ok','province_list':province_list})

        else:
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:
                    #这个是获取父级对象
                    parent_model = Area.objects.get(id=area_id)
                    #获取父级对象对应的子对象级
                    sub_model_list = parent_model.subs.all()

                    sub_list = []

                    for sub_model in sub_model_list:
                        sub_list.append({'id':sub_model.id, 'name':sub_model.name})

                    sub_data ={'id':parent_model.id,'name':parent_model.name,'subs':sub_list}
                    cache.set('sub_data',sub_data)


                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '城市或区数据错误'})
                cache.set('sub_area_' + area_id, sub_data, 3600)

            return JsonResponse({'code':RETCODE.OK,'errmsg':'ok', 'sub_data':sub_data})






